package com.weige.hotel.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weige.hotel.mapper.HotelMapper;
import com.weige.hotel.pojo.Hotel;
import com.weige.hotel.pojo.HotelDoc;
import com.weige.hotel.pojo.PageResult;
import com.weige.hotel.pojo.RequestParams;
import com.weige.hotel.service.IHotelService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 聚合查询
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        //  准备request对象
        SearchRequest request = new SearchRequest("hotel");
        //  DSL
        buildBasicQuery(params, request);
        //  设置size
        request.source().size(0);
        //  聚合
        buildAggregation(request);
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response == null) {
            return null;
        }
        //  解析响应
        Map<String, List<String>> map = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        //  根据品牌名称，获取品牌结果
        List<String> brandList = getAggByName(aggregations, "brandAgg");
        map.put("brand", brandList);
        //  根据城市名称，获取品牌结果
        List<String> cityList = getAggByName(aggregations, "cityAgg");
        map.put("city", cityList);
        //  根据星级名称，获取品牌结果
        List<String> starList = getAggByName(aggregations, "starAgg");
        map.put("starName", starList);
        return map;
    }

    @Override
    public void deleteDocById(Long id) {
        DeleteRequest request = new DeleteRequest("hotel", id + "");
        DeleteResponse result = null;
        try {
            result = client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
        }
        System.out.println(result);
    }

    @Override
    public void insertOrUpdate(Long id) {
        //  根据id取数据库查询文档信息
        Hotel hotel = getById(id);
        HotelDoc doc = new HotelDoc(hotel);
        //  将doc对象转化成json格式字符串
        String jsonData = JSON.toJSONString(doc);
        //  构建添加文档的请求对象
        IndexRequest index = new IndexRequest("hotel").id(hotel.getId() + "");
        //  设置请求参数
        index.source(jsonData, XContentType.JSON);
        IndexResponse result = null;
        try {
            result = client.index(index, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);
    }

    /**
     * 自动补全
     *
     * @param prefix
     */
    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            //  准备request对象
            SearchRequest request = new SearchRequest("hotel");
            //  DSL
            request.source().suggest(new SuggestBuilder().addSuggestion("suggestions", SuggestBuilders.completionSuggestion("suggestion").prefix(prefix).skipDuplicates(true).size(10)));
            //  发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //  解析结果
            Suggest suggest = response.getSuggest();
            //  根据补全查询名称,获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //  获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //  遍历
            ArrayList<String> list = new ArrayList<String>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据条件获取品牌结果
     *
     * @param aggregations
     * @param brandAgg
     */
    private List<String> getAggByName(Aggregations aggregations, String brandAgg) {
        //  根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(brandAgg);
        //  获取桶对象
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //  遍
        ArrayList<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            //  获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    /**
     * 聚合条件
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
        request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(100));
        request.source().aggregation(AggregationBuilders.terms("starAgg").field("starName").size(100));
    }

    /**
     * 查询酒店数据
     */
    @Override
    public PageResult search(RequestParams params) {
        //  准备request对象
        SearchRequest request = new SearchRequest("hotel");
        //  DSL语句
        buildBasicQuery(params, request);
        //  分页查询
        Integer page = params.getPage() == null ? 1 : params.getPage();
        Integer size = params.getSize() == null ? 5 : params.getSize();
        request.source().from((page - 1) * size).size(size);
        //  距离排序
        String location = params.getLocation();
        if (StringUtils.isNotBlank(location)) {
            request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
        }
        //  发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  解析响应对象
        return handleResponse(response);
    }

    /**
     * 复杂的DSL语句
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //  多条件查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //  关键字搜索
        String key = params.getKey();
        if (StringUtils.isBlank(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", params.getKey()));
            //  高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        }
        //  city
        if (StringUtils.isNotBlank(params.getCity())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        //  brand
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //  starName
        if (StringUtils.isNotBlank(params.getStarName())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //  price
        if (params.getMaxPrice() != null && params.getMinPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        //  用户评价排序
        if ("score".equals(params.getSortBy())) {
            request.source().sort("score", SortOrder.DESC);
        } else if ("price".equals(params.getSortBy())) {
            request.source().sort("price", SortOrder.ASC);
        }
        //  竞价排名
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQueryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true), ScoreFunctionBuilders.weightFactorFunction(5))});
        //  设置DSL条件
        request.source().query(functionScoreQueryBuilder);
    }

    /**
     * 解析响应对象
     */
    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        //  获取总条数
        long total = searchHits.getTotalHits().value;
        ArrayList<HotelDoc> list = new ArrayList<>();
        if (searchHits != null) {
            //  遍历
            for (SearchHit hit : searchHits) {
                //  获取文档JSON
                String jsonData = hit.getSourceAsString();
                //  反序列化
                HotelDoc hotelDoc = JSON.parseObject(jsonData, HotelDoc.class);
                //  解析高亮
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    // 根据字段名获取高亮结果
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null) {
                        // 获取高亮值
                        String name = highlightField.getFragments()[0].string();
                        // 覆盖非高亮结果
                        hotelDoc.setName(name);
                    }
                }
                //  获取排序值
                Object[] sortValues = hit.getSortValues();
                if (sortValues.length > 0) {
                    Object sortValue = sortValues[0];
                    hotelDoc.setDistance(sortValue);
                }
                list.add(hotelDoc);
            }
        }
        return new PageResult(total, list);
    }
}
